<template>
  <el-dialog
    :title="titleMap[mode]"
    v-model="visible"
    :width="1000"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-form ref="dialogForm" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="cName">
            <el-input
              v-model="form.cName"
              placeholder="请输入用户姓名"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="cAccount">
            <el-input
              v-model="form.cAccount"
              placeholder="请输入账号"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="cPhone">
            <el-input
              v-model="form.cPhone"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="fDepartmentIds">
            <!-- <treeselect
              :multiple="true"
              :normalizer="normalizer2"
              :options="options"
              v-model="form.fDepartmentIds"
              :sort-value-by="'ORDER_SELECTED'"
              :default-expand-level="1"
              :flat="true"
              placeholder="请选择上级"
              noOptionsText="暂无数据"
              noChildrenText="暂无数据"
            /> -->
            <!-- <el-tree-v2
              v-model="form.fDepartmentIds"
              :data="depts"
              value-key="id"
              node-key="id"
              :render-after-expand="false"
              check-strictly
              :props="defaultProps"
              placeholder="请选择，默认为所有检察机关"
              clearable
              filterable
              accordion
              style="width: 100%"
            /> -->

            <treeselect
              v-model="form.fDepartmentIds"
              :multiple="true"
              :options="depts"
              :normalizer="normalizer2"
              placeholder=""
              style="width: 100%"
            >
            </treeselect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号">
            <el-input
              v-model="form.cCardNo"
              placeholder="请输入身份证号"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="fRoleIds">
            <el-select
              style="width: 100%"
              v-model="form.fRoleIds"
              multiple
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.cRoleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="所属区域" prop="fTaskAreaId">
              <el-cascader
                style="width: 100%"
                :options="areaList"
                v-model="form.fTaskAreaId"
                :props="{
                  checkStrictly: true,
                  label: 'cName',
                  value: 'id',
                  children: 'childrenList',
                  emitPath: false
                }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row> -->

      <el-row v-if="mode === 'add'">
        <el-col :span="24">
          <el-form-item label="密码" prop="cPassword">
            <el-input
              v-model="form.cPassword"
              type="text"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="岗位" prop="cChargeValue">
            <el-select
              v-model="form.cChargeValue"
              placeholder="请选择岗位"
              clearable
              @change="changeCharge"
            >
              <el-option
                v-for="{ raw } in dict.type.gwsx"
                :key="raw.cName"
                :label="raw.cName"
                :value="raw.cValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        v-if="mode != 'show'"
        type="primary"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>

<script>
import Treeselect from "vue3-treeselect";
import "vue3-treeselect/dist/vue3-treeselect.css";
export default {
  emits: ["success", "closed"],
  data() {
    var newPass = (rule, value, callback) => {
      if (value.toLowerCase() === "admin") {
        callback(new Error("账号不能设置为admin"));
      } else {
        callback();
      }
    };
    return {
      mode: "add",
      titleMap: {
        add: "新增用户",
        edit: "编辑用户",
        show: "查看",
      },
      defaultProps: {
        value: "id",
        label: "cDepartmentName",
        children: "children",
      },
      visible: false,
      isSaveing: false,

      //表单数据
      form: {
        cName: "",
        cAccount: "",
        // fIsPartyMember: "",
        // fTaskAreaId: null,
        cPhone: "",
        cWorkUnit: "",
        cCardNo: "",
        cPassword: "",
        fDepartmentIds: [],
        fRoleIds: [],
      },
      //验证规则
      rules: {
        // fPartyOrganizationId: [
        //   { required: true, message: "不能为空", trigger: "input" },
        // ],
        // cCardNo: [
        //   { required: true, message: "请输入身份证号", trigger: "blur" },
        //   {
        //     pattern:
        //       /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
        //     message: "请输入合法身份证号",
        //     trigger: "blur",
        //   },
        // ],
        // cPhone: [
        //   { required: true, message: "手机号不能为空", trigger: "blur" },
        // ],
        // cName: [
        //   { required: true, message: "用户姓名不能为空", trigger: "blur" },
        // ],
        // cAccount: [
        //   { required: true, message: "账号不能为空", trigger: "blur" },
        //   { required: true, validator: newPass, trigger: "blur" },
        // ],
        // roleIds: [
        //   { required: true, message: "用户角色不能为空", trigger: "blur" },
        // ],
        // cPassword: [
        //   { required: true, message: "用户密码不能为空", trigger: "blur" },
        //   {
        //     pattern:
        //       /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/,
        //     message:
        //       "请输入8位（包括）以上字符，包含数字、大小写字母、特殊字符中的至少3种",
        //     trigger: "change",
        //   },
        // ],
        // fRoleIds: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "角色不能为空",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        // fDepartmentIds: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "部门不能为空",
        //     trigger: ["blur", "change"],
        //   },
        // ],
      },
      //所需数据选项
      groups: [],
      groupsProps: {
        value: "id",
        multiple: true,
        checkStrictly: true,
      },
      // depts: [],
      deptsProps: {
        value: "id",
        checkStrictly: true,
      },
    };
  },
  props: {
    depts: {
      type: Array,
      default: [],
    },
    roleOptions: {
      type: Array,
      default: [],
    },
  },
  components: {
    Treeselect,
  },
  mounted() {
    // this.getGroup();
    // this.getDept();
  },
  methods: {
    // 数据格式转换
    normalizer2(node) {
      // 去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.cDepartmentName,
        children: node.children,
      };
    },
    //显示
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    //加载树数据
    async getGroup() {
      var res = await this.$API.system.role.list.get();
      this.groups = res.data.rows;
    },
    async getDept() {
      var res = await this.$API.system.user.GetDepartmentList.get();
      this.depts = res.content.list;
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;
          this.form.cPassword = this.$TOOL.crypto
            .MD5(this.form.cPassword)
            .toUpperCase();
          try {
            await (this.mode === "add"
              ? this.$API.system.user.AddSystemUser.post(this.form)
              : this.$API.system.user.UpdateSystemUser.post(this.form));
            this.isSaveing = false;
            this.$emit("success", this.form, this.mode);
            this.visible = false;
            this.$message.success("操作成功");
          } catch (error) {
            this.visible = false;
            // this.$alert(error, "提示", { type: "error" });
          }

          // if (res.code == 200) {
          //   this.$emit("success", this.form, this.mode);
          //   this.visible = false;
          //   this.$message.success("操作成功");
          // } else {
          //   this.$alert(res.message, "提示", { type: "error" });
          // }
        } else {
          return false;
        }
      });
    },
    //表单注入数据
    setData(data) {
      // this.form.id = data.id;
      // this.form.userName = data.userName;
      // this.form.avatar = data.avatar;
      // this.form.name = data.name;
      // this.form.group = data.group;
      // this.form.dept = data.dept;

      //可以和上面一样单个注入，也可以像下面一样直接合并进去
      if (data.departments.length) {
        data.fDepartmentIds = data.departments.map(
          (item) => item.fDepartmentId
        );
      }
      if (data.roles.length) {
        data.fRoleIds = data.roles.map((item) => item.fRoleId);
      }
      Object.assign(this.form, data);
    },
  },
};
</script>

<style></style>
